import {handleSql} from '../../database/mysql/index.js'


class roleTypesModel {
    constructor() {
        this.tableName = 'role_types';
    }
    
    // 根据角色id返回完整角色信息
    async showDetailRoleInfo(roleCodeList){
        if (!roleCodeList || roleCodeList.length === 0) {
            return [];
        }
        let tuple = '(' + JSON.parse(roleCodeList).join(',') + ')'
        const sql = `SELECT * FROM ${this.tableName} 
                WHERE roleCode IN ${tuple}`
        let result = handleSql(sql)
        return result
    }


    // 查询某个用户可见的的角色信息
    async searchRoleList(userId,roleName = '%') {
        const sql = `SELECT * FROM ${this.tableName} 
                     WHERE (userId IS NULL OR userId = ?) AND roleName LIKE '${roleName}'`
        let result = handleSql(sql,[userId])
        return result
    }


    // 新增自定义角色信息  ————  每个用户独有
    async addRoleMessage({userId, roleName}) {
        // 查找当前用户下的该角色是否已经存在
        let existingRole = await this.searchRoleList(userId,roleName)
         if (existingRole.length > 0) {
            return false
        }
        const sql = `INSERT INTO ${this.tableName}(userId,roleName) 
                     VALUES (?,?)`
        let result = await handleSql(sql,[userId,roleName])

        if(result.affectedRows == 1){
            return result.insertId
        }else{
            return false
        }
    }
}   

export default new roleTypesModel();